/**
 * Created by hdt3213 on 16-9-9.
 */

function judge(step) {
    var x0 = step[0], y0 = step[1], role = step[2];
    var x, y, stones;
    if (model.history.length > LEN * LEN) {
        return DROWN;
    }
    // horizon, right
    stones = 1;
    y = y0;
    x = x0 + 1;
    while (x < LEN) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        } 
        else {
            break;
        }
        x++;
    }
    // last stone on the edge
    if (stones == 5) {
        return role;
    }
    // left
    x = x0 - 1;
    while (x >= 0) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        x--;
    }
    if (stones == 5) {
        return role;
    }
    // vertical, up
    stones = 1;
    x = x0;
    y = y0 + 1;
    while (y < LEN) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        y++;
    }
    if (stones == 5) {
        return role;
    }
    // down
    y = y0 - 1;
    while (y >= 0) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        y--;
    }
    if (stones == 5) {
        return role;
    }
    // nw-se, south-east
    stones = 1;
    x = x0 - 1;
    y = y0 - 1;
    while (x >= 0 && y >= 0) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        x--;
        y--;
    }
    if (stones == 5) {
        return role;
    }
    // north-west
    x = x0 + 1;
    y = y0 + 1;
    while (x < LEN && y < LEN) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        x++;
        y++;
    }
    if (stones == 5) {
        return role;
    }
    // north-east
    stones = 1;
    x = x0 + 1;
    y = y0 - 1;
    while ( x < LEN && y >= 0) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        x++;
        y--;
    }
    if (stones == 5) {
        return role;
    }
    // south-west
    x = x0 - 1;
    y = y0 + 1;
    while (x >= 0 && y < LEN) {
        if (stones == 5) {
            return role;
        }
        if (model.board[x][y] == role) {
            stones += 1;
        }
        else {
            break;
        }
        x--;
        y++;
    }
    if (stones ==  5) {
        return role;
    }
    return VACANT;
}
